<script setup>
import { ref, onMounted, computed } from 'vue'
import { getAllStudentsAPI, addStudentAPI, updateStudentAPI, deleteStudentAPI } from '@/api/admin'
import { ElMessage } from 'element-plus'

const studentList = ref([])
const loading = ref(false)

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = computed(() => studentForm.value.studentId ? '编辑学生' : '新增学生')
const studentForm = ref({
  studentNo: '',
  name: '',
  gender: '',
  email: '',
  phone: '',
  classInfo: ''
})
const formRef = ref(null)

// 表单校验规则
const rules = {
  studentNo: [
    { required: true, message: '请输入学号', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
  ],
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    // 可以添加更严格的手机号码格式校验
  ],
  classInfo: [
    { required: true, message: '请输入班级信息', trigger: 'blur' }
  ]
}

// 获取所有学生列表
const getAllStudents = async () => {
  loading.value = true
  try {
    const { data } = await getAllStudentsAPI()
    if (data.code === 200) {
      studentList.value = data.data
    } else {
      ElMessage.error(data.msg || '获取学生列表失败')
    }
  } catch (error) {
    console.error('获取学生列表失败:', error)
    ElMessage.error('获取学生列表失败')
  } finally {
    loading.value = false
  }
}

// 显示新增/编辑弹窗
const showDialog = (student = null) => {
  if (student) {
    // 编辑
    studentForm.value = { ...student }
  } else {
    // 新增
    studentForm.value = {
      studentId: null,
      studentNo: '',
      name: '',
      gender: '',
      email: '',
      phone: '',
      classInfo: ''
    }
  }
  dialogVisible.value = true
}

// 确认新增/编辑
const confirmDialog = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const api = studentForm.value.studentId ? updateStudentAPI : addStudentAPI
        if(!studentForm.value.studentId){
          delete studentForm.value.studentId
        }
        // delete params.studentId
        const { data } = await api(studentForm.value)

        if (data.code === 200) {
          ElMessage.success(studentForm.value.studentId ? '学生信息更新成功！' : '学生添加成功！')
          dialogVisible.value = false
          getAllStudents() // 刷新列表
        } else {
          ElMessage.error(data.msg || (studentForm.value.studentId ? '学生信息更新失败' : '学生添加失败'))
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 删除学生
const deleteStudent = async (studentId) => {
  loading.value = true
  try {
    const { data } = await deleteStudentAPI(studentId)
    if (data.code === 200) {
      ElMessage.success('学生删除成功！')
      getAllStudents() // 刷新列表
    } else {
      ElMessage.error(data.msg || '学生删除失败')
    }
  } catch (error) {
    console.error('学生删除失败:', error)
    ElMessage.error('学生删除失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getAllStudents()
})
</script>

<template>
  <div class="student-management-container">
    <div class="header">
      <h2>学生管理</h2>
      <el-button type="primary" @click="showDialog()">新增学生</el-button>
    </div>

    <el-table v-loading="loading" :data="studentList" style="width: 100%">
      <el-table-column prop="studentId" label="ID" width="80" />
      <el-table-column prop="studentNo" label="学号" width="120" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="gender" label="性别" width="80" />
      <el-table-column prop="email" label="邮箱" width="180" />
      <el-table-column prop="phone" label="电话" width="150" />
      <el-table-column prop="classInfo" label="班级信息" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="showDialog(scope.row)">编辑</el-button>
          <el-popconfirm
            title="确定删除该学生吗？"
            confirm-button-text="确定"
            cancel-button-text="取消"
            @confirm="deleteStudent(scope.row.studentId)"
          >
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑学生弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="studentForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="学号" prop="studentNo">
          <el-input v-model="studentForm.studentNo" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="studentForm.gender" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="studentForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="studentForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="班级" prop="classInfo">
          <el-input v-model="studentForm.classInfo" placeholder="请输入班级信息" />
        </el-form-item>
        <!-- 编辑时可能需要禁用学号和ID字段 -->
        <el-form-item v-if="studentForm.studentId" label="ID">
            <el-input v-model="studentForm.studentId" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDialog">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<style scoped>
.student-management-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

h2 {
  margin: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 